package mil.af.amc.adpetracker.dao.hibernate;

import mil.af.amc.adpetracker.dao.RosDao;
import mil.af.amc.adpetracker.model.AdpeAccount;
import mil.af.amc.adpetracker.model.Ros;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.NonUniqueResultException;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Hibernate implementation of ROS DAO
 *
 * @author TSgt Jason Ferguson
 */
@Repository("rosDao")
public class HibernateRosDao extends HibernateGenericDao<Ros> implements RosDao {

    private static final Log log = LogFactory.getLog(Ros.class);

    public HibernateRosDao() {
        super(Ros.class);
    }

    @SuppressWarnings({"unchecked"})
    public Ros getByTrackingNumber(String trackingNumber) {

        Criteria rosCriteria = sessionFactory.getCurrentSession().createCriteria(Ros.class);
        rosCriteria.add(Restrictions.eq("trackingNumber", trackingNumber));

        Ros result = null;
        try {
            result = (Ros) rosCriteria.uniqueResult();
        } catch (NonUniqueResultException e) {
            log.debug("getByTrackingNumber() threw NonUniqueResultException", e);
            return null;
        }
        catch (HibernateException e) {
            log.debug("getByTrackingNumber() threw HibernateException");
        }

        return result;
//        if (results.size() == 0) {
//            return null;
//        } else {
//            return results.get(0);
//        }
    }

    @SuppressWarnings({"unchecked"})
    public List<Ros> getByAdpeAccount(AdpeAccount acct) {

        Criteria rosCriteria = sessionFactory.getCurrentSession().createCriteria(Ros.class);
        rosCriteria.add(Restrictions.eq("adpeAccount", acct));

        List<Ros> results = rosCriteria.list();

        return results;
        //return getHibernateTemplate().findByCriteria(crit);
    }
}
